<template>
  <div>
    <el-form ref="form" :model="form" label-width="80px" :rules="rules">
      <el-form-item label="所属学科" prop="subjectID">
        <el-select v-model="form.subjectID" placeholder="请选择">
          <el-option v-for="item in SubjectList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标签名称" prop="tagName">
        <el-input v-model="form.tagName"></el-input>
      </el-form-item>
    </el-form>
    <div class="issure">
      <el-button @click="$emit('close')">取消</el-button>
      <el-button type="primary" @click="hSubmit">确定</el-button>
    </div>
  </div>
</template>

<script>
import { detail, add, update } from '@/api/hmmm/tags'
import { simple } from '@/api/hmmm/subjects'

export default {
  props: {
    id: {
      type: Number,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data () {
    return {
      form: {
        subjectID: '',
        tagName: ''
      },
      SubjectList: [],
      rules: {
        subjectID: [
          { required: true, message: '请选择所属学科', trigger: 'change' }
        ],
        tagName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.setSubjectList()
    this.upDateForm()
  },
  methods: {
    // 获取简单的学科列表
    async setSubjectList () {
      try {
        const res = await simple()
        this.SubjectList = res.data
      } catch (e) {
        console.log(e)
      }
    },
    // 数据回填
    async upDateForm () {
      if (!this.isEdit) return
      try {
        const res = await detail(this.id)
        this.form = res.data
      } catch (e) {
        console.log(e)
      }
    },
    // 点击确定
    async hSubmit () {
      const bl = await this.$refs.form.validate().catch(e => e)
      if (!bl) return
      try {
        // 修改
        if (this.isEdit) {
          await update(this.form)
          this.$message.success('修改成功')
        } else {
          // 添加
          await add(this.form)
          this.$message.success('添加成功')
        }
        this.$emit('close')
        this.$emit('upData')
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 修改
    hEdit (id) {
      this.curId = id
      this.isEdit = true
      this.dialogVisible = true
    }
  }
}
</script>

<style scoped>
.issure {
  display: flex;
  justify-content: flex-end;
}
</style>
